package com.hutu.scoring;

import cn.hutool.json.JSONUtil;
import com.hutu.model.dto.question.QuestionContentDTO;
import com.hutu.model.entity.AccountAnswer;
import com.hutu.model.entity.App;
import com.hutu.model.entity.Question;
import com.hutu.model.entity.ScoringResult;
import com.hutu.model.enums.AppTypeEnum;
import com.hutu.service.QuestionService;
import com.hutu.service.ScoringResultService;
import com.hutu.utils.ScoringUtils;
import com.hutu.utils.UserThreadLocal;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 自定义策略策略
 */
@Component
@RequiredArgsConstructor
public class CustomEvaluationStrategy extends ScoringStrategy {

    private final QuestionService questionService;

    private final ScoringResultService scoringResultService;

    @Override
    public AccountAnswer doScore(List<String> choices, App app) throws Exception {
        // 根据应用id来获取题目信息
        Question question = questionService.findQuestionByAppId(app.getId());
        // 获取所有题目
        String questionContent = question.getQuestionContent();
        // 将题目信息转换为QuestionContentDTO对象
        List<QuestionContentDTO> questionContentDTOList = JSONUtil.toList(questionContent, QuestionContentDTO.class);
        // 根据应用id来获取结果
        List<ScoringResult> scoringResults = scoringResultService.findScoringResultByAppId(app.getId());
        ScoringResult bestScoreResult = ScoringUtils.findBestScoreResult(choices, questionContentDTOList, scoringResults);
        AccountAnswer  accountAnswer = new AccountAnswer();
        BeanUtils.copyProperties(bestScoreResult,accountAnswer,"id");
        accountAnswer.setAppType(app.getAppType());
        accountAnswer.setScoringStrategy(app.getScoringStrategy());
        accountAnswer.setResultId(bestScoreResult.getId());
        accountAnswer.setChoices(JSONUtil.toJsonStr(choices));
        // TODO 获取当前用户
        accountAnswer.setUserId(UserThreadLocal.get());
        return accountAnswer;
    }

    @Override
    public AppTypeEnum getAppTypeEnum() {
        return AppTypeEnum.TEST;
    }

}
